﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FileWatcher
{
    public class RichtextFileIncrementWatcher
    {
        private RichTextBox richTextBox = null;
        private string filePath = string.Empty;
        private FileSystemWatcher fileSystemWatcher;
        private long position = 0;

        public RichtextFileIncrementWatcher(RichTextBox aRichTextBox, string afilePath)
        {
            this.richTextBox = aRichTextBox;
            this.filePath = afilePath;
            position = 0;

            // 初始化FileSystemWatcher
            fileSystemWatcher = new FileSystemWatcher
            {
                Path = Path.GetDirectoryName(filePath),
                Filter = Path.GetFileName(filePath),
                NotifyFilter = NotifyFilters.LastWrite
            };

            fileSystemWatcher.Changed += OnLogChanged;
            fileSystemWatcher.EnableRaisingEvents = true;

            // 初始加载文件内容
            LoadLogFile();
        }

        private void AppendText(string text)
        {
            if (text != null)
            {
                // 需要在UI线程中更新RichTextBox
                if (richTextBox.InvokeRequired)
                {
                    richTextBox.Invoke(new Action<string>(AppendText), text);
                }
                else
                {
                    richTextBox.AppendText(text + Environment.NewLine);
                    richTextBox.ScrollToCaret(); // 滚动到最后
                }
            }
        }
        private void LoadLogFile()
        {
            if(File.Exists(filePath))
            {
                try
                {
                    // 打开文件流
                    using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                        // 指定从第10个字节开始读取
                        fileStream.Seek(position, SeekOrigin.Begin);

                        AppendText(reader.ReadToEnd());
                        // 获取当前字节位置
                        position = reader.BaseStream.Position;
                    }
                }
                catch (IOException ex)
                {
                    //MessageBox.Show($"无法读取文件: {ex.Message}");
                    throw;
                }
            }
        }

        private void OnLogChanged(object sender, FileSystemEventArgs e)
        {
            // 延迟读取，以防止文件正在被写入时读取失败
            System.Threading.Thread.Sleep(100);
            LoadLogFile();
        }
    }
}
